<template>
  <view class="containerzi">
    <view @click="openPopup()">
      <view style="margin-bottom: 8rpx;">
        <text class="required-star">*</text>
        访厂发起日期
      </view>
      <up-input placeholder="访厂发起日期" border="surround" v-model="value"
        :customStyle="{ width: '90vw', pointerEvents: 'none' }" readonly></up-input>
    </view>

    <!--  日期选择器  -->
    <up-datetime-picker title="选择访厂发起日期" :show="show" v-model="dateValue" mode="date" @confirm="confirm"
      :closeOnClickOverlay="true" @close="closePopup" @cancel="show = false"></up-datetime-picker>

    <!--  客户访厂表  -->
    <view>
      <view style="margin-bottom: 8rpx;margin-top: 30rpx;">
        <text class="required-star">*</text>
        客户访厂表
      </view>
      <view>
        <scroll-view scroll-x="true" class="scroll-view">
          <view class="table-container">
            <table class="mobile-table order-table">
              <thead>
                <tr>
                  <!-- <th class="sticky-header">序号</th> -->
                  <th v-for="(item, index) in orderList" :key="index" class="nowrap">
                    <view style="display:flex;">
                      <text v-if="item.required" class="required-star">*</text>
                      <view>{{ item.title }}</view>
                    </view>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, rowIndex) in tableData" :key="rowIndex" @click="clickorder(row, rowIndex)">
                  <!-- <td class="sticky-col">{{ rowIndex + 1 }}</td> -->
                  <td v-for="(header, colIndex) in orderList" :key="colIndex" class="nowrap"
                    :class="{ highlight: header.field === 'orderNum' }">
                    {{ row[header.field] }}
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 订单列表弹窗 -->
    <up-popup :z-index="99999" :show="showOrderListPopup" mode="right" @close="showOrderListPopup = false"
      :customStyle="{ height: '100vh', width: '100vw', borderRadius: '16rpx 0 0 16rpx' }">
      <up-navbar title="选择订单" @leftClick="showOrderListPopup = false" placeholder
        :customStyle="{ backgroundColor: '#fff', borderBottom: '1px solid #f5f5f5' }"></up-navbar>
      <view class="search-box">
        <u-input v-model="searchKeyword" placeholder="输入订单号或客户名称搜索" clearable @change="handleSearchInput"></u-input>
      </view>
      <view class="popup-containerd">

        <!-- #ifdef H5 -->
        <view style="height: 20rpx"></view>
        <!-- #endif -->

        <!-- #ifdef APP-PLUS -->
        <view style="height: 20rpx"></view>
        <!-- #endif -->

        <scroll-view scroll-y class="popup-scroll" @scrolltolower="loadMoreOrders">
          <view v-for="(order, index) in filteredOrders" :key="order.id" class="order-item"
            @click="selectOrderItem(order)">
            <view class="order-info">
              <text class="order-label">订单编号：</text>
              <text class="order-value">{{ order.order_sum }}</text>
            </view>
            <view class="order-arrow">
              <u-icon name="arrow-right" color="#999" size="16"></u-icon>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>

    <!-- 选择订单弹出层 -->
    <up-popup :show="showOrderPopup" mode="right" @close="showOrderPopup = false">
      <view class="popup-container">
        <up-navbar :placeholder="false" :title="'订单信息 第' + (currentRowIndex + 1) + '行数据'"
          @leftClick="showOrderPopup = false" placeholder></up-navbar>
        <!-- #ifdef H5 -->
        <view style="height: 60rpx"></view>
        <!-- #endif -->

        <!-- #ifdef APP-PLUS -->
        <view style="height: 8vh"></view>
        <!-- #endif -->
        <scroll-view scroll-y class="popup-scroll">
          <view class="popup-content">
            <up-form :model="currentOrder" :rules="orderRules" ref="orderForm" label-position="top">
              <up-form-item v-for="item in orderList" :key="item.field" :label="item.title" :required="item.required"
                :prop="item.field">
                <up-input :disabled="item.disabled" @click="item.field === 'orderNum' ? openOrderListPopup() : null"
                  v-model="currentOrder[item.field]" :placeholder="`请输入${item.title}`"></up-input>
              </up-form-item>
            </up-form>
            <up-button type="primary" @click="validateOrderForm" style="margin-bottom: 20rpx">保存</up-button>
          </view>
        </scroll-view>
      </view>
    </up-popup>

    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>

<script>
import { GetgylList, BaseDatagylList } from '@/apis/SupplyChain/orderAfterSales'
import { useUserStore } from "@/pinia-store/user.js";
import { mapStores } from 'pinia';
export default {
  name: "customersVisitFactory",
  data() {
    return {
      modalShow: false,
      show: false,
      dateValue: Number(new Date()),
      dateMode: '',
      value: '',
      orderList: [
        {
          title: '所在部门',
          field: 'orderNum',
          required: true
        },
        {
          title: '销售人员',
          field: 'pickDate',
          required: true,
        },
        {
          title: '客户全称',
          field: 'department',
          required: true,
        },
        {
          title: '客户类型',
          field: 'salesPerson',
          required: true,
        },
        {
          title: '访厂人数',
          field: 'customerName',
          required: true,
        },
        {
          title: '访厂园区',
          field: 'arrivalDate',
          required: true,
        },
        {
          title: '访厂日期',
          field: 'arrivalDate',
          required: true,
        },
        {
          title: '到园区具体时间',
          field: 'arrivalDate',
          required: true,
        },
        {
          title: '访厂相关资料',
          field: 'arrivalDate',
          required: true,
        },
        {
          title: '访厂相关要求',
          field: 'arrivalDate',
          required: true,
        },
        {
          title: '备注',
          field: 'notes'
        }
      ], // 订单-客户信息
      tableData: [
        {

        },

      ], // 订单-客户信息
      productList: [
      ], // 产品信息
      productData: [
        {},
      ],
      // 订单选择列表
      orderOptions: [],
      // 弹出层控制
      showOrderPopup: false,
      showOrderEditPopup: false,

      // 当前操作的数据
      currentRowIndex: null,
      // 订单校验规则
      orderRules: {
        orderNum: [{ required: true, message: '请输入所在部门', trigger: 'change' }],
        pickDate: [{ required: true, message: '请输入销售人员', trigger: 'change' }],
        department: [{ required: true, message: '请输入客户全称', trigger: 'change' }],
        salesPerson: [{ required: true, message: '请输入客户类型', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入访厂人数', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入访厂园区', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入访厂日期', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入到园区具体时间', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入访厂相关资料', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入访厂相关要求', trigger: 'change' }]
      },
      // 产品校验规则
      productRules: {
      },
      // 初始化当前订单数据
      currentOrder: {
        orderNum: '',
        pickDate: '',
        department: '',
        salesPerson: '',
        customerName: '',
        arrivalDate: '',
        notes: ''
      },
      // 初始化当前产品数据
      currentProduct: {
      },
      pageNum: 1,
      pageSize: 15,
      total: 0,
      allGylorderNO: [],
      showOrderListPopup: false,
      isLoadingOrders: false,
      noMoreOrders: false,
      searchKeyword: '',
      tempOrderData: null,
      tempProductData: null,
    }
  },
  created() {
    uni.setStorageSync('orderAfterSalesData', null);
    uni.setStorageSync('customersVisitFactory', null);
    // this.gGetgylList()
  },
  computed: {
    ...mapStores(useUserStore),
    filteredOrders() {
      if (!this.searchKeyword) {
        return this.allGylorderNO; // 没有搜索关键词时返回全部数据
      }
      const keyword = this.searchKeyword.toLowerCase();
      return this.allGylorderNO.filter(order => {
        return (
          (order.order_sum && order.order_sum.toLowerCase().includes(keyword)) ||
          (order.customer_name && order.customer_name.toLowerCase().includes(keyword))
        );
      });
    }
  },
  methods: {
    handleSearchInput() {
      // 重置分页参数
      this.pageNum = 1;
      this.noMoreOrders = false;

      // 如果有搜索关键词，使用本地过滤
      if (this.searchKeyword) {
        return;
      }

      // 没有搜索关键词时重新加载数据
      this.allGylorderNO = [];
      this.loadMoreOrders();
    },
    // 打开弹窗时重置分页
    openOrderListPopup() {
      this.pageNum = 1
      this.allGylorderNO = []
      this.noMoreOrders = false
      this.showOrderListPopup = true
      this.loadMoreOrders()
    },

    async loadMoreOrders() {
      // 如果有搜索关键词，不执行上拉加载
      if (this.searchKeyword) return;
      // 防止重复加载或已加载全部
      if (this.isLoadingOrders || this.noMoreOrders) return;

      this.isLoadingOrders = true;
      try {
        const res = await GetgylList({
          token: this.userStore.user.token,
          type: 1,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderNumber: ''
        });

        if (res.status == 1) {
          // 确保数据格式正确
          const records = res.data?.records || [];
          this.total = res.data?.total || 0;

          // 处理第一页加载的情况
          if (this.pageNum === 1) {
            this.allGylorderNO = records;
          } else {
            this.allGylorderNO.push(...records);
          }

          // 判断是否还有更多数据
          if (records.length < this.pageSize || this.allGylorderNO.length >= this.total) {
            this.noMoreOrders = true;
          } else {
            this.pageNum += 1;
          }
        } else {
          uni.showToast({
            title: res.message || '加载失败',
            icon: 'none'
          });
        }
        this.modalShow = false
      } catch (err) {
        this.modalShow = false
        console.error('加载订单列表失败:', err);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.modalShow = false
        this.isLoadingOrders = false;
      }
    },
    // 选中订单
    selectOrderItem(order) {
      this.searchKeyword = ''
      // 将选中的订单数据填充到当前编辑的订单表单中
      this.currentOrder = {
        ...this.currentOrder,
        orderNum: order.order_sum || '', // 订单编号
      };
      this.gBaseDatagylList(order.order_sum)
      // 关闭订单选择弹窗
      this.showOrderListPopup = false;
    },
    async gBaseDatagylList(value) {
      try {
        this.modalShow = true;
        const res = await BaseDatagylList({
          token: this.userStore.user.token,
          type: 2,
          orderNum: value,
        });

        if (res.status === 1 && res.data) {
          const orderData = res.data;

          // 暂存订单数据到临时变量
          this.tempOrderData = {
            orderNum: orderData.orderSum || '',
            pickDate: orderData.pickDate || '',
            department: orderData.department || '',
            salesPerson: orderData.salesPerson || '',
            customerName: orderData.customerName || '',
            arrivalDate: orderData.arrivalDate || '',
            notes: '',
          };

          // 暂存产品数据到临时变量
          this.tempProductData =
            orderData.items && orderData.items.length > 0
              ? orderData.items.map((item) => ({
                parkName: '',
                productName: item.productName || '',
                skuName: item.skuName || '',
                piece: item.piece || '',
                grossWeight: item.weightTotal || '',
                weight: item.weight || '',
                desc: item.price || '',
                saleType: '退货',
                compensationQuantity: '',
                discountPrice: '',
                actualPayableAmount: '',
                reason: '',
                show: false, // 添加这个字段
              }))
              : [];

          // 更新当前订单表单数据（仅用于显示）
          this.currentOrder = { ...this.tempOrderData };
        }
      } catch (error) {
        console.error('获取订单详情出错:', error);
      } finally {
        this.modalShow = false;
      }
    },
    openPopup() {
      this.show = true;
    },
    closePopup() {
      this.show = false;
    },
    // 选中时间
    confirm(event) {
      var date = this.formatTimestampToYYMMDD(event.value);
      this.value = date;
      this.show = false;
    },
    // 打开选择订单弹窗
    openOrderSelect() {
      this.showOrderPopup = true
    },

    // 选择订单
    selectOrder(order) {
      this.tableData = [order]
      this.showOrderPopup = false
    },

    // 点击订单行
    clickorder(row, rowIndex) {
      this.currentOrder = {
        ...this.currentOrder, // 保留初始化结构
        ...row // 覆盖实际数据
      }
      this.currentRowIndex = rowIndex
      this.showOrderPopup = true
    },

    // 校验订单表单
    validateOrderForm() {
      this.$refs.orderForm.validate().then((res) => {
        if (res) {
          // 校验通过后，将临时数据更新到表格中
          if (this.tempOrderData && this.tempProductData) {
            this.tableData = [this.tempOrderData];
            this.productData = this.tempProductData;

            // 清空临时数据
            this.tempOrderData = null;
            this.tempProductData = null;

            // 保存到本地缓存
            uni.setStorageSync('customersVisitFactory', {
              orderData: this.tableData,
              productData: this.productData,
              date: this.value,
            });

            // 关闭弹窗
            this.showOrderPopup = false;
          }
        }
      }).catch((errors) => {
        uni.showToast({
          title: '请填写完整订单信息',
          icon: 'none',
        });
      });
    },

    // 时间戳转换
    formatTimestampToYYMMDD(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear().toString();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hour = ('0' + date.getHours()).slice(-2);
      const minute = ('0' + date.getMinutes()).slice(-2);
      if (this.dateMode === 'date') {
        return `${year}-${month}-${day}`;
      } else if (this.dateMode === 'datetime') {
        return `${year}-${month}-${day} ${hour}:${minute}`;
      } else if (this.dateMode === 'year-month') {
        return `${year}-${month}`;
      }
      return `${year}-${month}-${day}`; // 返回 YYMMDD 格式的字符串
    }
  }
}
</script>
<style scoped lang="scss">
.containerzi{
  background-color: #ffffff
}

.order-item {
  padding: 20rpx;
  border-bottom: 1px solid #eee;
}

.loading-text,
.no-more-text {
  text-align: center;
  color: #888;
  padding: 20rpx 0;
}

/* 隐藏字段样式 */
.hidden-field {
  display: none;
}

::v-deep uni-button {
  margin-left: 0 !important;
  margin-right: 10rpx !important;
  border: none !important;
}

.table-container {
  width: 100%;
}

/* 订单表格专属优化 */
.order-table {

  th,
  td {
    width: auto;

    &:first-child {
      width: auto;
    }
  }

  /* 交替行背景色 */
  tr:nth-child(even) td {
    background-color: #fafafa;
  }

  /* 重要数据突出显示 */
  .highlight {
    color: #e74c3c;
    font-weight: 500;
  }
}

.scroll-view {
  width: 95vw;
  white-space: nowrap;
  padding: 10rpx 0;
}

.mobile-table {
  width: auto;
  min-width: 100%;
  border-collapse: separate;
  border-spacing: 0;

  th,
  td {
    padding: 16rpx 24rpx;
    border-bottom: 1px solid #eee;
    font-size: 26rpx;
    line-height: 1.4;
  }

  th {
    background: #f1f2f4;
    color: #333;
    font-weight: 500;
    position: relative;

    &:not(:first-child)::after {
      content: "";
      position: absolute;
      right: 0;
      top: 10%;
      height: 80%;
      width: 1px;
      background: #ddd;
    }
  }

  td {
    color: #666;
    background: #fff;
  }

  .sticky-header {
    position: sticky;
    left: 0;
    z-index: 2;
    width: auto;
  }

  .sticky-col {
    position: sticky;
    left: 0;
    background: #f9f9f9;
    z-index: 1;
  }
}

.nowrap {

  white-space: nowrap;
}

.required-star {
  color: #e74c3c;
  margin-right: 4rpx;
  font-size: 28rpx;
  vertical-align: middle;
}

:required {
  border-left: 4rpx solid #e74c3c;
}


.popup-content {
  padding: 30rpx;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;

  .popup-header {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    text-align: center;
  }

  .order-item {
    padding: 20rpx;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;

    &:active {
      background-color: #f5f5f5;
    }
  }
}


.popup-container {
  width: 100vw;
  height: 100%;
  background-color: #f3f3f3;
  display: flex;
  flex-direction: column;
}

.popup-scroll {
  flex: 1;
  height: auto;
  overflow-y: auto;
}

.popup-content {
  padding: 30rpx;
  background: #fff;
}

.popup-header-fixed {
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1px solid #f5f5f5;
  position: sticky;
  top: 0;
  z-index: 10;
}

::v-deep .up-form-item__error {
  color: #e74c3c;
  font-size: 24rpx;
  margin-top: 8rpx;
}




.order-item {
  padding: 24rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
    background-color: #f5f5f5 !important;
  }
}

.order-info {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 28rpx;
  line-height: 1.5;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-label {
  color: #666;
  min-width: 140rpx;
}

.order-value {
  color: #333;
  font-weight: 500;
}

.loading-text,
.no-more-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 26rpx;

  text {
    margin-top: 16rpx;
  }
}

.u-page {
  padding: 0;
}

.u-cell-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 8rpx;
}

.u-cell-group__title__text {
  font-weight: bold;
}



.popup-containerd {
  background-color: #f5f5f5;
  padding: 0 20rpx;
  height: calc(100vh - 100rpx);
}

.popup-scroll {
  height: 100%;
}

.search-box {
  //margin-bottom: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 10rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.popup-scroll {
  height: calc(100% - 80rpx);
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  display: flex;
  flex-direction: column;
  transition: all 0.2s;

  &:active {
    background-color: #f8f8f8;
    transform: scale(0.99);
  }
}

.order-info {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 28rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-label {
  color: #666;
  width: 140rpx;
}

.order-value {
  color: #333;
  flex: 1;
  font-weight: 500;
}

.order-arrow {
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
}

.load-more,
.no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 26rpx;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.empty-tip {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
}
</style>
